package com.xxw.springbootencrypt.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xxw.springbootencrypt.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

/*
* 请求参数的解密操作
* RequestBodyAdvice可以理解为在@RequestBody之前需要进行的操作
* */
@Component
@ControllerAdvice(basePackages = "com.xxw.springbootencrypt.controller")
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    RsaUtil rsaUtil;

    /*
    * supports 定义什么注解生效，默认 @RequestBody
    * */
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }


    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        
        String dealData = null;
        Map<String,String> dataMap = (Map)o;
        String srcData = dataMap.get("data");
        dealData = new String(rsaUtil.decryptData(srcData.getBytes()));

        // 字符串转对象
        JSONObject jsonObject = JSONObject.parseObject(dealData);

        // 返回对象数据
        return jsonObject;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return null;
    }
}

